package com.platform.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.annotation.DataScope;
import com.platform.common.constant.UserConstants;
import com.platform.common.core.domain.Ztree;
import com.platform.common.core.text.Convert;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.StringUtils;
import com.platform.common.utils.redis.RedisUtil;
import com.platform.module.domain.BaseCalorimeterData;
import com.platform.module.domain.BaseCalorimeterType;
import com.platform.module.domain.LinkConcentratorMeter;
import com.platform.module.mapper.BaseCalorimeterDataMapper;
import com.platform.module.mapper.BaseCalorimeterTypeMapper;
import com.platform.module.mapper.LinkConcentratorMeterMapper;
import com.platform.module.service.IBaseCalorimeterDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 热量表设备数据Service业务层处理
 *
 * @author wangqi
 * @date 2020-07-13
 */
@Service
public class BaseCalorimeterDataServiceImpl extends ServiceImpl<BaseCalorimeterDataMapper, BaseCalorimeterData> implements IBaseCalorimeterDataService
{
    @Autowired
    private BaseCalorimeterDataMapper baseCalorimeterDataMapper;

    @Autowired
    private BaseCalorimeterTypeMapper baseCalorimeterTypeMapper;

    @Autowired
    private LinkConcentratorMeterMapper linkConcentratorMeterMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 将采集器和热表关联存放到redis
     */
    @PostConstruct
    public void init() {
        List<BaseCalorimeterData> list = baseCalorimeterDataMapper.selectBaseCalorimeterDataList(new BaseCalorimeterData());
        for(BaseCalorimeterData calorimeterData : list){
            redisUtil.hset("calorimeterData", calorimeterData.getCalorimeterId(), calorimeterData);
        }
    }

    /**
     * 查询热量表设备数据列表
     *
     * @param baseCalorimeterData 热量表设备数据
     * @return 热量表设备数据
     */
    @Override
    public List<BaseCalorimeterData> selectBaseCalorimeterDataList(BaseCalorimeterData baseCalorimeterData)
    {
        return baseCalorimeterDataMapper.selectBaseCalorimeterDataList(baseCalorimeterData);
    }

    /**
     * 查询热量表设备数据
     *
     * @param calorimeterId 热表id
     * @return 热量表设备数据
     */
    @Override
    public BaseCalorimeterData selectBaseCalorimeterData(String calorimeterId)
    {
        //从redis中获取热表信息
        return (BaseCalorimeterData) redisUtil.hget("calorimeterData", calorimeterId);
    }

    /**
     * 新增热量表设备数据
     *
     * @param baseCalorimeterData 热量表设备数据
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBaseCalorimeterData(BaseCalorimeterData baseCalorimeterData)
    {
        saveLink(baseCalorimeterData);
        baseCalorimeterData.setCreateTime(DateUtils.getNowDate());
        //将热表数据保存到redis
        redisUtil.hset("calorimeterData", baseCalorimeterData.getCalorimeterId(), baseCalorimeterData);
        return baseCalorimeterDataMapper.insert(baseCalorimeterData);
    }

    /**
     * 修改热量表设备数据
     *
     * @param baseCalorimeterData 热量表设备数据
     * @return 结果
     */
    @Override
    @Transactional
    public int updateBaseCalorimeterData(BaseCalorimeterData baseCalorimeterData)
    {
        saveLink(baseCalorimeterData);
        baseCalorimeterData.setUpdateTime(DateUtils.getNowDate());
        //将热表数据保存到redis
        redisUtil.hset("calorimeterData", baseCalorimeterData.getCalorimeterId(), baseCalorimeterData);
        return baseCalorimeterDataMapper.updateById(baseCalorimeterData);
    }

    /**
     * 保存热表和集中器的对应关系
     * @param baseCalorimeterData
     */
    @Transactional
    void saveLink(BaseCalorimeterData baseCalorimeterData){
        if(baseCalorimeterData.getConcentratorId()!=null && !baseCalorimeterData.getConcentratorId().equals("")) {
            if(redisUtil.hHasKey("concentratorMeter", baseCalorimeterData.getCalorimeterId())){
                String concentrarotId = redisUtil.hget("concentratorMeter", baseCalorimeterData.getCalorimeterId()).toString();
                if(!concentrarotId.equals(baseCalorimeterData.getConcentratorId())) {
                    linkConcentratorMeterMapper.delete(new QueryWrapper<LinkConcentratorMeter>().eq("calorimeter_id", baseCalorimeterData.getCalorimeterId()));
                    LinkConcentratorMeter linkConcentratorMeter = new LinkConcentratorMeter();
                    linkConcentratorMeter.setConcentratorId(baseCalorimeterData.getConcentratorId());
                    linkConcentratorMeter.setCalorimeterId(baseCalorimeterData.getCalorimeterId());
                    linkConcentratorMeterMapper.insert(linkConcentratorMeter);
                }
            }else{
                LinkConcentratorMeter linkConcentratorMeter = new LinkConcentratorMeter();
                linkConcentratorMeter.setConcentratorId(baseCalorimeterData.getConcentratorId());
                linkConcentratorMeter.setCalorimeterId(baseCalorimeterData.getCalorimeterId());
                linkConcentratorMeterMapper.insert(linkConcentratorMeter);
            }
            redisUtil.hset("concentratorMeter", baseCalorimeterData.getCalorimeterId(), baseCalorimeterData.getConcentratorId());
        }
    }

    /**
     * 删除热量表设备数据对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteBaseCalorimeterDataByIds(String ids)
    {
        for(String id : Arrays.asList(Convert.toStrArray(ids))){
            redisUtil.hdel("calorimeterData", id);
        }
        return baseCalorimeterDataMapper.deleteBatchIds(Arrays.asList(Convert.toStrArray(ids)));
    }


    /**
     * 导入热量表信息数据
     *
     * @param calorimeterDataList 热量表信息数据
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importBaseCalorimeterData(List<BaseCalorimeterData> calorimeterDataList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(calorimeterDataList) || calorimeterDataList.size() == 0)
        {
            throw new BusinessException("导入热量表信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BaseCalorimeterData calorimeterData : calorimeterDataList)
        {
            try
            {
                //查询热量表类型
                QueryWrapper<BaseCalorimeterType> queryWrapper = new QueryWrapper<BaseCalorimeterType>();
                queryWrapper.eq("type_name",calorimeterData.getTypeName());
                BaseCalorimeterType calorimeterType = baseCalorimeterTypeMapper.selectOne(queryWrapper);
                if(calorimeterType!=null){
                    calorimeterData.setTypeId(calorimeterType.getTypeId());
                }

                //查询热量表信息是否存在
                BaseCalorimeterData calorimeter = baseCalorimeterDataMapper.selectById(calorimeterData.getCalorimeterId());
                if (StringUtils.isNull(calorimeter))
                {
                    calorimeterData.setCreateBy(operName);
                    calorimeterData.setCreateTime(DateUtils.getNowDate());
                    this.insertBaseCalorimeterData(calorimeterData);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、热量表 " + calorimeterData.getCalorimeterId() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    calorimeterData.setUpdateBy(operName);
                    calorimeterData.setUpdateTime(DateUtils.getNowDate());
                    this.updateBaseCalorimeterData(calorimeterData);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、热量表 " + calorimeterData.getCalorimeterId() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、热量表 " + calorimeterData.getCalorimeterId() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、热量表 " + calorimeterData.getCalorimeterId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 根据条件分页查询已分配热表列表
     *
     * @param calorimeterData 热表信息
     * @return 热表信息集合信息
     */
    @Override

    public List<BaseCalorimeterData> selectAllocatedList(BaseCalorimeterData calorimeterData)
    {
        return baseCalorimeterDataMapper.selectAllocatedList(calorimeterData);
    }


    /**
     * 根据条件分页查询未分配热表角色列表
     *
     * @param baseCalorimeterData 热表信息
     * @return 热表信息集合信息
     */
    @Override

    public List<BaseCalorimeterData> selectUnallocatedList(BaseCalorimeterData baseCalorimeterData)
    {
        return baseCalorimeterDataMapper.selectUnallocatedList(baseCalorimeterData);
    }

    /**
     * 校验热表id是否唯一
     *
     * @param baseCalorimeterData 热表信息
     * @return 结果
     */
    @Override
    public String checkCalorimeterDataCodeUnique(BaseCalorimeterData baseCalorimeterData)
    {
        String status = StringUtils.isNull(baseCalorimeterData.getStatus()) ? "" : baseCalorimeterData.getStatus();
        BaseCalorimeterData calorimeterData = baseCalorimeterDataMapper.selectById(baseCalorimeterData.getCalorimeterId());
        if (StringUtils.isNotNull(calorimeterData)&& !baseCalorimeterData.getCalorimeterId().equals(status))
        {
            return UserConstants.CALORIMETER_ID_NOT_UNIQUE;
        }
        return UserConstants.CALORIMETER_ID_UNIQUE;
    }

    /**
     * 查询热表数
     *
     * @return 所有阀门信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectCalorimeterTree()
    {
        List<BaseCalorimeterType> calorimeterTypeList = baseCalorimeterTypeMapper.selectList(new QueryWrapper<>());
        List<Ztree> ztrees = initZtree(calorimeterTypeList);
        return ztrees;
    }

    /**
     * 对象转阀门树
     *
     * @param calorimeterTypeList 阀门类型列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<BaseCalorimeterType> calorimeterTypeList)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (BaseCalorimeterType baseCalorimeterType : calorimeterTypeList)
        {
            BaseCalorimeterData baseCalorimeterData = new BaseCalorimeterData();
            baseCalorimeterData.setCalorimeterId(baseCalorimeterType.getTypeId().toString());
            baseCalorimeterData.setTypeId(baseCalorimeterType.getTypeId());
            baseCalorimeterData.setTypeName(baseCalorimeterType.getTypeName());

            Ztree ztree = new Ztree();
            ztree.setId(baseCalorimeterData.getCalorimeterId());
            ztree.setpId(baseCalorimeterData.getTypeId());
            ztree.setName(baseCalorimeterData.getTypeName());
            ztree.setTitle(baseCalorimeterData.getTypeName());
            ztrees.add(ztree);

            List<BaseCalorimeterData> calorimeterList = baseCalorimeterDataMapper.selectList(new QueryWrapper<BaseCalorimeterData>().eq("type_id", baseCalorimeterType.getTypeId()));
            if(calorimeterList!=null && calorimeterList.size()>0){
                for (BaseCalorimeterData calorimeterData : calorimeterList){
                    ztree = new Ztree();
                    ztree.setId(calorimeterData.getCalorimeterId());
                    ztree.setpId(calorimeterData.getTypeId());
                    ztree.setName(calorimeterData.getCalorimeterId());
                    ztree.setTitle(calorimeterData.getCalorimeterId());
                    ztrees.add(ztree);
                }
            }
        }
        return ztrees;
    }

    /**
     * 根据条件分页查询已分配热表列表
     *
     * @param calorimeterData 热表信息
     * @return 热表信息集合信息
     */
    @Override
    public List<BaseCalorimeterData> selectAllocatedSubList(BaseCalorimeterData calorimeterData)
    {
        return baseCalorimeterDataMapper.selectAllocatedSubList(calorimeterData);
    }


    /**
     * 根据条件分页查询未分配热表角色列表
     *
     * @param baseCalorimeterData 热表信息
     * @return 热表信息集合信息
     */
    @Override
    public List<BaseCalorimeterData> selectUnallocatedSubList(BaseCalorimeterData baseCalorimeterData)
    {
        return baseCalorimeterDataMapper.selectUnallocatedSubList(baseCalorimeterData);
    }




}
